/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-07-04 17:01:38
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-07-05 10:42:57
 * @FilePath: /lesson/lesson_net/blog_tcp/TcpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>

#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <ctime>
#include <cstdarg>
#include <fstream>
#include <cstring>
#include <pthread.h>



#define BACKLOG 5

class TcpServer
{
public:
    TcpServer(int port):_port(port)
    {
    }
    void InitServer()
    {
        if ((_listensockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        {
            // 1、创建套接字
            std::cerr << "socket error" << std::endl;
            exit(-1);
        }

        // bind前创建sockaddr_in结构体:用于填充网络信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 2、绑定 bind 套接字
        if (bind(_listensockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            perror("error: ");
            std::cerr << "bind fail" << std::endl;
            exit(-2);
        }

        // 3、将套接字设置为监听状态
        if (listen(_listensockfd, BACKLOG) < 0)
        {
            std::cerr << "listen fail" << std::endl;
            exit(-3);
        }
    }

    void Start()
    {
        for(;;)
        {
            // 获取连接
            struct sockaddr_in peer;// 创建struct sockaddr_in结构体的原因： 用于存储客户端的地址信息
            memset(&peer,0,sizeof(peer));
            socklen_t len=sizeof(peer);
            
            int sock=accept(_listensockfd,(struct sockaddr*)&peer,&len);

            if(sock<0)
            {
                std::cerr << "accept error, continue next" << std::endl;
                continue;
            }
            std::string client_ip = inet_ntoa(peer.sin_addr);
            int client_port = ntohs(peer.sin_port);

            std::cout<<"get a new link->"<<sock<<" ["<<client_ip<<"]:"<<client_port<<std::endl;// 打印出文件描述符，IP地址，端口号port
            
        }
    }

    ~TcpServer()
    {
        if (_listensockfd >= 0)
        {
            close(_listensockfd);
        }
    }

private:
    int _listensockfd; // 监听套接字
    int _port;         // 端口号
};